<?php
class AdminMaster{

    static $_LIST_ = false;
    static $_EDIT_ = false;
    static $_ADD_ = false;
    static $_DELETE_ = false;
    static $_PG_LIST_ = array();
    
    function __construct(){
		
	}

	function __destruct(){

	}
    
    // This function will check the request module is allowed to be accessed by the user or not
    // If user is not alllowed to access he will be thrown to invalid access page !!!!
    public static function checkModuleAccessability(){
        // if user is logged in then check for the module accessbility  //
        if( AdminMaster::is_admin_loggedin() ){         
            $modName = AdminMaster::getCurrentModuleName();                        
            if( AdminMaster::isAccessable($modName, $userType=1) ){
                //  module is accessable do nothing //           
            }else{
                header("Location: "._SITE_ADMIN_URL_.'auth-error.php');
                exit;
            }
        }
    }
    
    
    public static function getCurrentModuleName(){
            
        $scriptName = $_SERVER['SCRIPT_NAME'];
        $scriptName = dirname($scriptName);
        $tmparr = explode('/',$scriptName);
        $modName = $tmparr[count($tmparr)-1];
        return $modName;
        
    }
    
    public static function getCurrentScriptName(){
            
        $scriptName = $_SERVER['SCRIPT_NAME'];
        return $scriptName = basename($scriptName);        
        
    }
    
    public static function getModuleId($module){
        $moduleRec = CommonUtility::getData(null, 'admin_modules', array('module'=>$module));
        if( $moduleRec ){            
            $record = $moduleRec[0];
            $moduleId = $record['id'];                        
            return $moduleId;
        }
        return false;    
    }
    
    public static function userAccessList($currmodId){
        $groupid = AdminMaster::getSessionByKey('access_group');
        if( !empty($groupid) ){
            $currentfile = AdminMaster::getCurrentScriptName();
            $result = CommonUtility::getDataById($groupid, 'access_group');   
            $module_id =  explode(',', $result['module_id']);
            
            $modid = array();
            foreach( $module_id as $val ){
                $tmp = explode('::', $val);
                $modid[$tmp[0]] = $tmp[1];
                $tmpArr[] = $tmp[0];
            }
            $modids = implode(',',$tmpArr);            
            $qry = "select * from admin_module_page where module_id in ($modids) ";
            $rs = MyDB::$db->Execute($qry);
            if( $rs ){
                while( $row = $rs->fetchRow()){
                    $arrPG[$row['module_id']] = array('1'=>$row['list_page'], '3'=>$row['edit_page'], '2'=>$row['add_page']);
                }
            }
            $accessPG = array();
            foreach( $arrPG as $key => $val ){
                if( array_key_exists($key, $modid) ){
                    $arrA = explode('-', $modid[$key]);
                    //if( in_array('1', $arrA) )       
                    $accessPG[] = $arrPG[$key][1];          //  listing permission is granted automatically
                    if( in_array('2', $arrA) )       $accessPG[] = $arrPG[$key][2];
                    if( in_array('3', $arrA) )       $accessPG[] = $arrPG[$key][3];
                    
                    if ($currmodId == $key ) {
                        if( in_array('1', $arrA) )       AdminMaster::$_LIST_ = true;
                        if( in_array('2', $arrA) )       AdminMaster::$_ADD_ = true;
                        if( in_array('3', $arrA) )       AdminMaster::$_EDIT_ = true;
                        if( in_array('4', $arrA) )       AdminMaster::$_DELETE_ = true;
                    }

                }                
            }
            AdminMaster::$_PG_LIST_ = $accessPG;            
        }
        
    }
    // chec accessability of looged in user for provided module
    // user type is adminuser 1 or vendor agent 2
    public static function isAccessable($module, $userType){
        
        $modId = AdminMaster::getModuleId($module);
        if( !$modId ){ return true; }       //   this means page user is accessing is not in the access module :: allow him
        
        AdminMaster::userAccessList($modId);
        $pagename = AdminMaster::getCurrentScriptName($module);
        //print_r(AdminMaster::$_PG_LIST_);exit;
        if( in_array($pagename, AdminMaster::$_PG_LIST_)){
            return true;
        }else{
            return false;
        }
        
                        
        $groupid = AdminMaster::getSessionByKey('access_group');
        if( !empty($groupid) ){
            if( $userType==1 ){             // admin user 
            $modId = $modId . '::';
            $qry = "select * from access_group where id=".MyDB::$db->qstr($groupid )." and module_id like '%$modId%' ";
                $rs = MyDB::$db->Execute($qry);
                if( $rs ){
                    if( $rs->fetchRow()){
                        return true;       
                    }
                }
            }
            else if ( $userType==2 ){       // vendor agent            
                
            }
        }
        return false;
    }
    
    public static function getAllowedModule(){
        $groupid = AdminMaster::getSessionByKey('access_group');
        if( $module_res = CommonUtility::getDataById($groupid, 'access_group') ){
            $module_ids = $module_res['module_id'];
            $arrMod = explode(',', $module_res['module_id']);
            $modid = array();            
            foreach( $arrMod as $val ){
                $tmp = explode('::', $val);
                $modid[] = $tmp[0];
            }           
            $module_ids = implode(',', $modid);                             
            $qry = "select * from admin_modules where id in($module_ids) and status='1'";
            $rs = MyDB::$db->Execute($qry);
            if( $rs ){
                while( $row = $rs->fetchRow() ){                    
                    $tmpArr[] = $row['module'];
                }
                return $tmpArr;
            }
        }
        return false;        
    }
    
    public static function getSessionByKey($key){
        return $_SESSION[$key];
    }
    
	public function getAdminDetail($uname,$pass){
		//Logger::log("Enter: AdminMaster::getAdminDetail() | Args: ");
		
		$qry = "select * from admin where username=".MyDB::$db->qstr($uname)." and password=".MyDB::$db->qstr($pass)." ";;
		$rs = MyDB::$db->Execute($qry);
		if( $rs ){
			$arr = $rs->fetchRow();
			return $arr;
		}
		return false;
		
		//Logger::log("Exit: AdminMaster::getAdminDetail()");
	}

	public function adminTracking(){
		//Logger::log("Enter: AdminMaster::getAdminDetail() | Args: ");
		$tm=date("Y-m-d h:i:s");		
		$ip = $_SERVER['REMOTE_ADDR'];
		$query=mysql_query("insert into admin_ip_tracking (admin_id,ip,login_time) values (".MyDB::$db->qstr($_SESSION['sess_admin_id']).','.MyDB::$db->qstr($ip).','.MyDB::$db->DBDate($tm).")");
		$rs = MyDB::$db->Execute($qry);
		
		//Logger::log("Exit: AdminMaster::getAdminDetail()");
	}

	public static function is_admin_loggedin(){
		if(isset($_SESSION['sess_admin_name']) && ($_SESSION['sess_admin_name']!=""))
		{
				return true;
		}
		return false;
	}

	public function adminLastLoginInfo(){
		//Logger::log("Enter: AdminMaster::getAdminDetail() | Args: ");

		$qry="select * from admin_ip_tracking  where admin_id='".$_SESSION['sess_admin_id']."' order by login_time  desc limit 1,1";		
		$rs = MyDB::$db->Execute($qry);
		if( $rs ){
			$arr = $rs->fetchRow();
			return $arr;
		}
		return false;

		//Logger::log("Exit: AdminMaster::getAdminDetail()");
	}


	public static function changePassword($user_field_value,$OldPassword,$NewPassword)
	{
		$qry ="select * from admin where username = ".MyDB::$db->qstr($user_field_value)." and password = ".MyDB::$db->qstr($OldPassword);
		$rs = MyDB::$db->Execute($qry);
		if( $rs ){			
			if($arr = $rs->fetchRow())
			{
				$upd_str ="update admin set password = ".MyDB::$db->qstr($NewPassword)." where username = ".MyDB::$db->qstr($user_field_value);			  
				MyDB::$db->Execute($upd_str);
				return true;

			}else{
				return false;
			}	 
		}
		return false;	 
	}
    
    public static function getAccessModuleByIds($ids){
        
        $qry = "select * from admin_modules where id in ($ids)";
        $rs = MyDB::$db->Execute($qry);
        if( $rs ){
            $arr = $rs->GetArray();
            return $arr;
        }
        return false;      
    }
    
    public static function moduleList(){
        $qry = "select am.module, am.module_name, am.image_path, amp.list_page from admin_modules am join admin_module_page amp on am.id=amp.module_id where am.status='1' and parent_id='0'";
        $rs = MyDB::$db->Execute($qry);
        if( $rs ){
            $arr = $rs->GetArray();
            return $arr;
        }
        return false;              
    }
}
?>
